package org.example.controller;

import com.alibaba.fastjson.JSONObject;
import org.example.response.ApiResponse;
import org.example.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api")
public class VerificationCodeController {
    private static final String CAPTCHA_PREFIX = "captcha:";
    private static final String REQUEST_FLAG_PREFIX = "requestFlag:";
    private static final int CAPTCHA_EXPIRATION_TIME = 5 * 60; // 5 minutes
    private static final int REQUEST_FLAG_EXPIRATION_TIME = 60; // 1 minute

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 请求验证码
     */
    @PostMapping("/requestVerificationCode")
    public ApiResponse<String> requestVerificationCode(@RequestBody JSONObject emailObject) {
        String email = validateEmailRequest(emailObject);
        if (email == null) {
            return ApiResponse.notFound(400, "不合法的邮箱地址");
        }

        String captchaKey = CAPTCHA_PREFIX + email;
        String requestFlagKey = REQUEST_FLAG_PREFIX + email;

        // 检查请求频率
        if (Boolean.TRUE.equals(redisTemplate.hasKey(requestFlagKey))) {
            return ApiResponse.error("验证码请求过于频繁，请稍后再试！");
        }

        // 生成验证码并存储
        String code = generateVerificationCode();
        redisTemplate.opsForValue().set(captchaKey, code, CAPTCHA_EXPIRATION_TIME, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(requestFlagKey, "request", REQUEST_FLAG_EXPIRATION_TIME, TimeUnit.SECONDS);

        // 发送验证码
        try {
            emailUtil.sendEmail(email, "验证码", code);
            return ApiResponse.success("已成功发送验证码！");
        } catch (Exception e) {
            // 记录异常日志
            // log.error("发送验证码失败: {}", e.getMessage());
            return ApiResponse.error("发送验证码时发生错误，请稍后再试");
        }
    }

    /**
     * 验证请求中的邮箱地址
     */
    private String validateEmailRequest(JSONObject emailObject) {
        if (emailObject == null || !emailObject.containsKey("email")) {
            return null;
        }
        return emailObject.getString("email");
    }

    /**
     * 生成6位数的验证码
     */
    private String generateVerificationCode() {
        int min = 100000; // 最小的6位数
        int max = 999999; // 最大的6位数
        return String.valueOf(ThreadLocalRandom.current().nextInt(min, max + 1));
    }
}
